// 引入接口文件
import { addFun,editFun,queryInfo,monthInit,graphData,queryAreaAndCity,updateReason} from './groupMonthReportDetailServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
import { rstr2b64 } from '../../../../utils/md5'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'

// 初始默认状态
const defultState = {
  btnLoading: false,
  infoData:[],
  treeData: [],
  expandedKeys: [],
  autoExpandParent: true,
  loading: false,
  monthInitType: true,
  keys: 0,
  actionType: 'add',
  butShow: true,
  query: {
    id: '',
    title: '',//标题
    createTime: '',//创建时间
    createBy: '',//创建人
    updateBy: '',
    updateTime: '',
    status: '',
    month: '',
    areaId:'',
    areaName:'',
    cityId: '',
    cityName: '',
    data: {
      residentialConclusion:"",
      inventoryConclusion:"",
      landConclusion:"",
      supply:"",
      clinch:"",
      inventory:"",
      land:"",
      analysisResult:'',
      formNumber:[],
      formList:[],
      infoData: []
    },
  }
}

// 声明module
const tmpModule = {
  namespace: 'defaultModel',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if('' + tmpModule.pathname === '' + pathname){
          // 执行业务操作
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          if(query.actionType == 'check'|| query.actionType == 'edit'){
            dispatch({type: 'queryInfo',payload: {id:query.id}})
          }
          dispatch({type: 'queryAreaAndCity',payload: {}})
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
     // 初始化
     *monthInit({payload}, {put, select, call}){
          let {monthInitType,query,actionType} = yield select(state => state[tmpModule.namespace])
          if(!query.month){
            message.warning('请先选择时间')
            return
          }
          let params = { 
            month: query.month,
            status: actionType=='add'?'1':'2'
          }
          const { success,formList,formNumber,analysisResult} = yield call(monthInit, {...params})
          monthInitType = success
          yield put({type: 'updateStore',payload: {monthInitType}})
          if(success){
            let arr = []
            arr.push(formNumber)
            query.data.formNumber = arr
            for(var item of formList){
              for(var itemed of item.data){
                if(itemed.region){
                  itemed.city = itemed.city + itemed.region
                }
              }
            }
            query.data.formList = formList
            query.data.analysisResult = analysisResult
            yield put({type: 'graphData',payload: {}})
            yield put({
              type: 'updateStore',
              payload: {query}
            })
          }
      },
      // 获取图表数据
     *graphData({payload}, {put, select, call}){
          let {query,infoData} = yield select(state => state[tmpModule.namespace])
          if(!query.month){
            message.warning('请先选择时间')
            return
          }
          let params = { 
            month: query.month,
            areaId: query.areaId,
            areaName: query.areaName,
            cityId: query.cityId,
            cityName: query.cityName
          }
          const { success,result} = yield call(graphData, {...params})
          if(success){
            for(var item of result){
              let xingong = []
              let chengjiao = []
              let junjia = []
              let yuefen = []
              for(var itemed of item.data){
                xingong.push(itemed.addAcreage)
                chengjiao.push(itemed.transactionAcreage)
                junjia.push(itemed.averagePrice)
                yuefen.push(itemed.month)
              }
              item.xingong = xingong
              item.chengjiao = chengjiao
              item.junjia = junjia
              item.yuefen = yuefen
              let all = xingong.concat(chengjiao)
              // let max1= Math.floor(Math.max.apply(null,all))
              // let max2= Math.floor(Math.max.apply(null,item.junjia))
              let length1 = Math.floor(Math.max.apply(null,all)/10).toString().length
              let length2 = Math.floor(Math.max.apply(null,item.junjia)/10).toString().length
              let interval1= Math.floor(Math.max.apply(null,all)/Math.pow(10,length1))*Math.pow(10,length1)/5
              let interval2= Math.floor(Math.max.apply(null,item.junjia)/Math.pow(10,length2))*Math.pow(10,length2)/5
              let max1= Math.floor(Math.max.apply(null,all))+interval1
              let max2= Math.floor(Math.max.apply(null,item.junjia))+interval2
              let title = item.title
              item.option = {
                title:{
                  show:true, //显示策略，默认值true,可选为：true（显示） | false（隐藏）
                  text: title, //主标题文本，'\n'指定换行
                  x:'center'
                },
                grid: {
                  left: '8%',
                  right: '2%',
                  containLabel: true
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        crossStyle: {
                            color: '#999'
                        }
                    }
                },
                legend: {
                    data: ['新供面积（万m²）', '成交面积（万m²）', '成交均价（元/m²）'],
                    bottom: 0,
                },
                xAxis: [
                    {
                        type: 'category',
                        data: item.yuefen,
                        axisPointer: {
                            type: 'shadow'
                        },
                        axisLabel: {
                            rotate:40
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        min: 0,
                        max: max1,
                        scale: true,
                        // interval: interval1,
                        axisLabel: {
                            formatter: '{value}'
                        },
                        axisTick: {
                          show: false
                        },
                        axisLine: {
                            show: false
                        }
                    },
                    {
                        type: 'value',
                        min: 0,
                        max: max2,
                        scale: true,
                        // interval: interval2,
                        axisLabel: {
                            formatter: '{value}'
                        },
                        splitLine:{
                    　　　　show:false
                    　　},
                        axisTick: {
                            show: false
                        },
                        axisLine: {
                            show: false
                        }
                    }
                ],
                series: [
                    {
                        name: '新供面积（万m²）',
                        type: 'bar',
                        data: item.xingong,
                        itemStyle: {   
                          normal:{  
                              color: '#5b9bd5'
                          },
                        },
                    },
                    {
                        name: '成交面积（万m²）',
                        type: 'bar',
                        data: item.chengjiao,
                        itemStyle: {   
                          normal:{  
                              color: '#ed7d31'
                          },
                        },
                    },
                    {
                        name: '成交均价（元/m²）',
                        type: 'line',
                        data: item.junjia,
                        yAxisIndex: 1,
                        itemStyle : { normal: {label : {show: true}}}
                    }
                ]
              };
            }
            infoData = result
            yield put({
              type: 'updateStore',
              payload: {infoData}
            })
          }
      },
      // 获取树
      *queryAreaAndCity({payload}, {put, select, call}){
          let {treeData} = yield select(state => state[tmpModule.namespace])
          let params = {}
          const { success,result} = yield call(queryAreaAndCity, {...params})
          if(success){
            let arr =[]
            let dataList = []
            for(let key in result){
              if(result[key] instanceof Object){
                result[key].title=result[key].area;
              for(let i=0;i<result[key].children.length;i++){
                result[key].children[i].key=result[key].children[i].cityid;
                result[key].children[i].title=result[key].children[i].city;
              }
              arr.push(result[key])
              }
            }
            result.children = arr
            dataList.push(result)
            treeData = dataList
            yield put({
              type: 'updateStore',
              payload: {treeData}
            })
          }
      },
      // 查询记录
      *queryInfo({payload}, {put, select, call}){
          let {query,infoData,expandedKeys,treeData,autoExpandParent} = yield select(state => state[tmpModule.namespace])
          let params = { 
            id: payload.id,
          }
          const { success,result} = yield call(queryInfo, {...params})
          if(success){
            result.data = JSON.parse(result.data)
            infoData = result.data.infoData
            query = result
            autoExpandParent = true
            yield put({
              type: 'updateStore',
              payload: {query,infoData,autoExpandParent}
            })
            yield put({type: 'graphData',payload: {}})
          }
      },
      *updateReason({payload},{put,select,call}){
        let {butShow} = yield select(state => state[tmpModule.namespace])
        let params = { 
            id: payload.id,
            reason: payload.reason
        }
        let { success, msg, data } = yield call(updateReason, {...params})
        if(success){
          message.success('保存成功')
          butShow = true
          yield put({
            type: 'updateStore',
            payload: {butShow}
          })
        }
      },
      *submit({payload},{put,select,call}){
        let {loading,btnLoading,actionType,query,infoData} = yield select(state => state[tmpModule.namespace])
        if(payload.type=='保存'){
          query.status = '0'
          btnLoading = true
          yield put({type: 'updateStore', payload: {btnLoading}})
        }
        if(payload.type=='提交'){
          query.status = '1'
          loading = true
          yield put({type: 'updateStore', payload: {loading}})
        }
        query.createBy = localStorage.nickname
        query.createUser = localStorage.username
        query.data.infoData = infoData
        query.data = JSON.stringify(query.data)
        let params =  query
        if(actionType == 'add'){
          let { success, msg, data } = yield call(addFun, {...params})
          let flag = success.toString()
          if(flag){
            if(payload.type=='保存'){
              btnLoading = false
              yield put({type: 'updateStore', payload: {btnLoading}})
            }
            if(payload.type=='提交'){
              loading = false
              yield put({type: 'updateStore', payload: {loading}})
            }
          }
          if(success){
            message.success(payload.type=='保存'?'保存成功':'发布成功')
            hashHistory.push({
              pathname: '/home/predictManage/monthReport',
              query:  {tabsType:'2'}
            })
          }
        }
        if(actionType == 'edit'){
          let { success, msg, data } = yield call(editFun, {...params})
          let flag = success.toString()
          if(flag){
            if(payload.type=='保存'){
              btnLoading = false
              yield put({type: 'updateStore', payload: {btnLoading}})
            }
            if(payload.type=='提交'){
              loading = false
              yield put({type: 'updateStore', payload: {loading}})
            }
          }
          if(success){
            message.success(payload.type=='保存'?'保存成功':'发布成功')
            hashHistory.push({
              pathname: '/home/predictManage/monthReport',
              query:  {tabsType:'2'}
            })
          }
        }
      }
  },

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
